//
//  VideoList.m
//  kankanVideo
//
//  Created by wangbo on 6/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "VideoList.h"
#import "XMLParser.h"
#import "ASIHTTPRequest.h"
#import "GANTracker.h"


#define kCustomRowHeight  86
#define kCustomRowCount   7
#define kAppIconHeight    60
#define kAppIconWidth     80

@implementation VideoList
@synthesize entries;
@synthesize delegate;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)init{
    NSLog(@"=========videolist_init=========");
    self=[super init];
    lazyImages = [[MHLazyTableImages alloc] init];
    lazyImages.placeholderImage = [UIImage imageNamed:@"videolistback.png"];
    lazyImages.delegate = self;
    lazyImages.tableView=self.tableView;
    self.tableView.rowHeight=kCustomRowHeight;
    //myrequest=[[MyRequest alloc]init];
    
    return self;
}

-(void)myreloaddata:(NSString*)weburl withClassid:(NSString *)clsid{
    classid=clsid;
    NSLog(@"videolist_myreloaddata:%@",weburl);
    //[entries removeAllObjects];
    //[self.tableView reloadData];
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [app showAlert:@"正在加载"];
    [[MyRequest shareInstance]loaddataWithURL:weburl forObject:self];
    //[myrequest loaddataWithURL:weburl forObject:self];
}

-(void)loaddata:(NSString *)clsid needRefresh:(BOOL)flag{
    NSLog(@"loaddata_needrefresh!!!");
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [app showAlert:@"正在加载"];
    classid=clsid;
    currentpage=1;
    NSArray *arr=[[MyCoreData shareInstance]queryVideoList:clsid];
    //NSLog(@"%@",arr);
    if (flag||arr.count<20) {
        NSLog(@"refresh    ");
        [self loadVideoList];
    }else{
        NSLog(@"read memory!!!");
        NSMutableArray* arr1=[[NSMutableArray alloc]init];
        for (VideoListData *vd in arr) {
            NSMutableArray *tmp=[[NSMutableArray alloc]initWithCapacity:3];
            [tmp addObject:vd.title];
            [tmp addObject:vd.titleurl];
            [tmp addObject:vd.titlepic];
            [arr1 addObject:tmp];
        }
        self.entries=arr1;
        [self.tableView reloadData];
        [delegate playFirstVideo:[entries objectAtIndex:0]];
        //[delegate playFirstVideo:[[entries objectAtIndex:0] objectAtIndex:1] withTitle:[[entries objectAtIndex:0] objectAtIndex:0]];
        AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
        [app hideAlert];
    }
}

-(void)loadVideoList{
    //NSString *weburl=[NSString stringWithFormat:@"http://interface.kankanews.com/kkapi/mobile/mobileapi.php?m=vlist&cid=%@&pagesize=20&page=%d",classid,currentpage];
    NSString *weburl=[NSString stringWithFormat:@"http://interface.kankanews.com/kkapi/mobile/padapi.php?m=vlist&c=ios&cid=%@&page=%d",classid,currentpage];
    NSLog(@"loadVideoList:%@",weburl);
    [[MyRequest shareInstance]loaddataWithURL:weburl forObject:self];
}
-(void)requestFinishedHandler:(ASIHTTPRequest*)request{
    if(request.responseStatusCode==200){
        if (currentpage==1) {
            self.entries=[XMLParser parseVideoList:request.responseData];
            [[MyCoreData shareInstance]deleteVideoList:classid];
            [[MyCoreData shareInstance]insertVideoList:entries withClassid:classid];
        }else{
            [self.entries addObjectsFromArray:[XMLParser parseVideoList:request.responseData]];
        }
        lazyImages.noNeedDownloadRow=entries.count;
        [self.tableView reloadData];
        [delegate playFirstVideo:[entries objectAtIndex:0]];
        //[delegate playFirstVideo:[[self.entries objectAtIndex:0] objectAtIndex:1]];
    }
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    [app hideAlert];
}

-(void)requestFailedHandler:(ASIHTTPRequest *)request{
    NSError *err=request.error;
    NSLog(@"%@",err);
    NSLog(@"failed");
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"==========videolist_viewdidload==========");
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    NSLog(@"=====videolist_viewdidload=========");
    lazyImages.tableView=nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
-(void)dealloc{
    [entries release];
    lazyImages.delegate = nil;
	[lazyImages release];
	[super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
    // Return the number of rows in the section.
    int count = [entries count];
    //NSLog(@"count:%d",count);
    if (count == 0)
        return 0;  // enough rows to fill the screen
	else
		return count+1;
}
-(void)shareVideo:(id)sender{
    UIButton *btn=(UIButton*)sender;
    UITableViewCell *cell=(UITableViewCell *)[btn superview];
    int row=[self.tableView indexPathForCell:cell].row;
    //return [[self.entries objectAtIndex:row]objectAtIndex:2];
    [delegate shareVideo:[[self.entries objectAtIndex:row]objectAtIndex:1]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (entries.count>0) {
        static NSString* CellIdentifier = @"LazyTableCell";
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.font=[UIFont fontWithName:@"Arial" size:14];
            /*UIButton *btnshare=[UIButton buttonWithType:UIButtonTypeCustom];
            [btnshare setBackgroundImage:[UIImage imageNamed:@"fengxiang.png"] forState:UIControlStateNormal];
            [btnshare setFrame:CGRectMake(0, 0, 40, 40)];
            [btnshare addTarget:self action:@selector(shareVideo:) forControlEvents:UIControlEventTouchUpInside];*/
            [cell setBackgroundColor:[UIColor clearColor]];
            [cell.textLabel setBackgroundColor:[UIColor clearColor]];
            //cell.accessoryView=btnshare;
        }
        if(indexPath.row<entries.count){
            cell.textLabel.text = [[entries objectAtIndex:indexPath.row]objectAtIndex:0];
            [lazyImages addLazyImageForCell:cell withIndexPath:indexPath];
            //[cell.accessoryView setHidden:NO];
            [cell.imageView setHidden:NO];
        }else{
            cell.textLabel.text=@"更多";
            //[cell.accessoryView setHidden:YES];
            [cell.imageView setHidden:YES];
        }
        return cell;
    }else{
        return nil;
    }
}

#pragma mark -
#pragma mark UIScrollViewDelegate

- (void)scrollViewDidEndDragging:(UIScrollView*)scrollView willDecelerate:(BOOL)decelerate
{
	[lazyImages scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
	[lazyImages scrollViewDidEndDecelerating:scrollView];
}

#pragma mark -
#pragma mark MHLazyTableImagesDelegate

- (NSURL*)lazyImageURLForIndexPath:(NSIndexPath*)indexPath
{
	//AppRecord* appRecord = [self.entries objectAtIndex:indexPath.row];
	return [NSURL URLWithString:[[entries objectAtIndex:indexPath.row] objectAtIndex:2]];
}

- (UIImage*)postProcessLazyImage:(UIImage*)image forIndexPath:(NSIndexPath*)indexPath
{
    if (image.size.width != kAppIconWidth && image.size.height != kAppIconHeight)
	{
        CGSize itemSize = CGSizeMake(kAppIconWidth, kAppIconHeight);
		UIGraphicsBeginImageContextWithOptions(itemSize, YES, 0);
		CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
		[image drawInRect:imageRect];
		UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
		UIGraphicsEndImageContext();
		return newImage;
    }
    else
    {
        return image;
    }
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"videolist_didselect");
    if (indexPath.row<entries.count) {
        NSError *error;
        if (![[GANTracker sharedTracker] trackEvent:@"看看iospad"
                                             action:@"视频播放"
                                              label:[[entries objectAtIndex:indexPath.row]objectAtIndex:0]
                                              value:0
                                          withError:&error]) {
            NSLog(@"error in trackEvent");
            NSLog(@"视频播放_%@",[[entries objectAtIndex:indexPath.row]objectAtIndex:0]);
        }
        [delegate playMovieWithParam:[entries objectAtIndex:indexPath.row]];
        //[delegate playMovieWithURL:[[entries objectAtIndex:indexPath.row]objectAtIndex:1] withTitle:[[entries objectAtIndex:indexPath.row] objectAtIndex:0]];
    }else{
        currentpage++;
        [self loadVideoList];
    }
}

@end
